import requests
import re
import pandas as pd
import numpy as np

def cookieManager():
    file = open("cookie.csv", "r")
    df = pd.read_csv(file)
    data = np.array(df)
    for j in range(len(data)):
        headers = {
            "Referer": 'https://detail.tmall.com/item.htm?id=544636202128',
            "User-Agent": data[j][1],
            "cookie": data[j][0]
        }
        url = "https://rate.tmall.com/list_detail_rate.htm"
        urlparams = {
            "itemId": '544636202128',
            "sellerId": "3",
            "currentPage": str(1),
            "callback": "jsonp723"
        }
        r = requests.get(url, params=urlparams, headers=headers)
        match = re.search('"lastPage":(\d+)', r.text)
        if match is None:
            continue
        else:
            return headers
    s_g.Popup('储存所有cookie失效', font='黑体', text_color='red')  # cookie弹窗
    return None

def commentSort(url):
    start=url.find('id=')+3
    end=url.find('&')
    itemId = url[start:end]
    headers=cookieManager()
    url = "https://rate.tmall.com/list_detail_rate.htm"
    page = 1
    comLists = []
    dateLists = []
    urlparams = {
        "itemId": itemId,
        "sellerId": "3",
        "currentPage": str(page),
        "callback": "jsonp723"
    }
    r = requests.get(url, params=urlparams, headers=headers)
    match = re.search(r'"lastPage":(\d+)', r.text)
    if match is None:
        print("cookie失效")
        return None
    else:
        maxPage = int(match.group(1))
    while page < 21:
        if maxPage<page:
            break
        urlparams = {
            "itemId": itemId,
            "sellerId": "3",
            "currentPage": str(page),
            "callback": "jsonp723",
        }
        r = requests.get(url, params=urlparams, headers=headers)
        for list in (re.findall('"rateDate":"(.*?)"', r.text)):
            listed = list[0:10]
            dateLists.append(listed)
        comLists.extend(re.findall('"rateContent":"(.*?)"', r.text))
        page += 1
    finalList = []
    for i in range(len(dateLists)):
        finalList.append([dateLists[i], comLists[i]])
    return finalList

if __name__=='__main__':
     print(commentSort('//detail.tmall.com/item.htm?id=687870318222&ns=1&abbucket=13'))